/**
 * this framework base on jq 1.6.2
 **/
try {
    console.log('log');
} catch (e) {
    var console = {
        log: function () {
        }
    };
}

/**
 *@namespace
 **/
var gb = gb = gb || {};
(function () {
    gb.classes = {};
    gb.fn = {};
    gb.browser = {};
    gb.net = {};
    gb.window = {};
    gb.form = {};

    //===========
    // Class
    //===========
    var initializing = false;
    var fnTest = /xyz/.test(function () {
        xyz;
    }) ? /\b_super\b/ : /.*/;
    this.Class = function () {
    };
    Class.extend = function (prop) {
        var _super = this.prototype;
        initializing = true;
        var pty = new this();
        initializing = false;
        for (var name in prop) {
            pty[name] = typeof prop[name] == "function" &&
            typeof _super[name] == "function" && fnTest.test(prop[name]) ?
                (function (name, fn) {
                    return function () {
                        var tmp = this._super;
                        this._super = _super[name];
                        var ret = fn.apply(this, arguments);
                        this._super = tmp;
                        return ret;
                    };
                })(name, prop[name]) :
                prop[name];
        }
        function Class() {
            if (!initializing && this.ctor)
                this.ctor.apply(this, arguments);
        }

        Class.prototype = pty;
        Class.prototype.constructor = Class;
        Class.extend = arguments.callee;
        return Class;
    };
    gb.classes.Class = Class;

    //===========
    // Signal
    //===========
    gb.classes.Signal = gb.classes.Class.extend({
        _callBackFunArr: [],
        _callBackSelfArr: [],

        ctor: function () {
            this._callBackFunArr = [];
            this._callBackSelfArr = [];
        },
        add: function (callBackFn_, domain_) {
            var $have = false;
            for (var i = 0; i < this._callBackFunArr.length; i++) {
                if (this._callBackFunArr[i] == callBackFn_ && this._callBackSelfArr[i] == domain_) {
                    $have = true;
                    break;
                }
            }
            if (!$have) {
                this._callBackFunArr.push(callBackFn_);
                this._callBackSelfArr.push(domain_);
            }
        },
        addOnce: function (callBackFn_, domain_) {

        },
        remove: function (callBackFun_) {
            var index = this._callBackFunArr.indexOf(callBackFun_);
            if (index != -1) {
                this._callBackFunArr.splice(index, 1);
                this._callBackSelfArr.splice(index, 1);
            }
        },
        dispatch: function () {
            for (var i = 0; i < this._callBackFunArr.length; i++) {
                var $self = this._callBackSelfArr[i];
                var $fun = this._callBackFunArr[i];
                $fun.apply($self, arguments);
            }
        }
    });

    //===========
    // timer
    //===========
    gb.classes.Timer = gb.classes.Class.extend({
        _delay: null,
        _repeat: null,
        _interval: 0,
        _count: 0,
        _isStart: false,
        sgTimer: null,

        ctor: function (delay_, repeat_) {
            this._delay = delay_;
            this._repeat = repeat_;
            this.sgTimer = new gb.classes.Signal();
        },
        start: function () {
            if (this._isStart) return;
            gb.fn.clearLoop(this._interval);
//            clearInterval(this._interval);
            this._interval = gb.fn.loop(this._onTimerRun, this._delay, {self: this, aa: 123});
//            this._interval = setInterval(this._onTimerRun, this._delay, {self:this});
            this._isStart = true;
        },
        pause: function () {
            if (!this._isStart) return;
            gb.fn.clearLoop(this._interval);
//            clearInterval(this._interval);
            this._isStart = false;
        },
        stop: function () {
            gb.fn.clearLoop(this._interval);
//            clearInterval(this._interval);
            this._count = 0;
            this._isStart = false;
        },
        _onTimerRun: function (data_) {
            var $self = data_.self;
            $self._count++;
            if ($self._count == $self._repeat && $self._repeat != 0) $self.stop();
            $self.sgTimer.dispatch($self);
        }
    });

    //-----------------------------
    //  public function
    //-----------------------------
    //int转string
    gb.fn.intToString = function (int_, length_) {
        var $s = int_ + "";
        var $l = $s.length;
        if ($l < length_) {
            var $n = length_ - $l;
            for (var i = 0; i < $n; i++) {
                $s = "0" + $s;
            }
        }
        return $s;
    };
    gb.fn.randomNumber = function (min_, max_) {
        return Math.floor(Math.random() * (max_ - min_ + 1)) + min_;
    };
    gb.fn.limitNumber = function (num_, min_, max_) {
        num_ = num_ < min_ ? min_ : num_;
        num_ = num_ > max_ ? max_ : num_;
        return num_;
    };
    //查找数组中元素id
    gb.fn.getIdFromArray = function (element_, array_) {
        var $id = -1;
        for (var i = 0; i < array_.length; i++) {
            if (array_[i] == element_) $id = i;
        }
        return $id;
    };
    gb.fn.getCSSNumber = function (value_) {
        value_ = value_ == null ? 0 : Number(value_.substr(0, value_.length - 2));
        return value_;
    };
    gb.fn.getDomPosition = function (dom_) {
        var obj = dom_;

        var left = obj.offsetLeft;
        var top = obj.offsetTop;

        for (; obj = obj.offsetParent;) {
            top += obj.offsetTop;
            left += obj.offsetLeft;
        }
        return {x: left, y: top};
    };
    gb.fn.reverseArray = function (arr_) {
        var $arr = [];
        for (var i in arr_) {
            $arr.unshift(arr_[i]);
        }
        return $arr;
    };
    gb.fn.getAddressParam = function (key_) {
        var hrefstr, pos, parastr, para, tempstr;
        hrefstr = window.location.href;
        pos = hrefstr.indexOf("?");
        parastr = hrefstr.substring(pos + 1);
        para = parastr.split("&");
        tempstr = "";
        for (var i = 0; i < para.length; i++) {
            tempstr = para[i];
            pos = tempstr.indexOf("=");
            if (tempstr.substring(0, pos) == key_) {
                return tempstr.substring(pos + 1);
            }
        }
        return null;
    };
    gb.fn.setAddressFlag = function (flag_) {
        var $url = parent.location.href;
        var $baseUrl = $url.split('#')[0];
        parent.location.href = $baseUrl + "#" + flag_;
    };
    gb.fn.getAddressFlag = function () {
        var $url = parent.location.href;
        var $flag = $url.split('#')[1];

        $flag = $flag == null ? '' : $flag;
        $flag = $flag.replace('/', '');

        return $flag;
    };
    gb.fn.replaceStr = function (str_, replaceKey_, value_) {
        return str_.replace(replaceKey_, value_);
    };
    //setInterval
    var _loopIdMap = {};
    gb.fn.loop = function (fn_, delay_, parms_) {
        var $newFn = function () {
            fn_.call(window, parms_);
        };
        var $id = setInterval($newFn, delay_);
        return $id;
    };
    gb.fn.clearLoop = function (id_) {
        clearInterval(id_);
    };
    //
    gb.fn.getSwf = function (id_) {
        if (navigator.appName.indexOf("Microsoft") != -1) {
            return window[id_];
        } else {
            return document[id_];
        }
    };
    //
    gb.fn.deleAllSpace = function (str_) {
        return str_.replace(/\s+/g, "");
    }

    //-----------------------------
    // net
    //-----------------------------
    gb.net.ImgsLoader = gb.classes.Class.extend({
        _urlList: null,
        _imgsList: null,
        _loadedNum: 0,

        //timer var
        _timer: null,
        _runTimerNum: 0,
        _testPro: 0,

        progress: 0,

        sgProgress: null,
        sgComplete: null,

        ctor: function (urlList_) {
            this._urlList = urlList_;
            this._imgsList = [];

            this._timer = new gb.classes.Timer(1000 / 1000, 0);
            this._timer.sgTimer.add(this._onTimerEvt, this);

            this.sgProgress = new gb.classes.Signal();
            this.sgComplete = new gb.classes.Signal();
        },
        getImageById: function (id_) {
            return this._imgsList[id_];
        },
        load: function () {
            if (!this._urlList[this._loadedNum]) {
                return;
            }

            var $img = new Image();
            $img.self = this;
            $($img).bind('load', {self: this}, this._onImgLoaded);
            var $self = this;
            setTimeout(function () {
                $img.src = $self._urlList[$self._loadedNum];
            }, 0.01);

            this._imgsList[this._loadedNum] = $img;

            this._testPro = this._runTimerNum = 0;
            this._timer.start();
        },
        _onImgLoaded: function (e) {
            var $self = e.data.self;
            $self._loadedNum++;
            $self._timer.stop();
            $self._testPro = 0;
            $self.progress = $self._getProgress();

            if ($self._loadedNum < $self._urlList.length) {
                $self.sgProgress.dispatch({target: $self});
                $self.load();
            } else {
                $self._getProgress();
                $self.sgProgress.dispatch({target: $self});
                $self.sgComplete.dispatch({target: $self});
            }
        },
        _onTimerEvt: function (timer_) {
            var $pro = 0;
            this._runTimerNum++;

            for (var i = 0; i < this._runTimerNum; i++) {
                $pro += (1 - $pro) * .1;
            }
            this._testPro = $pro;
            this.sgProgress.dispatch({target: this});
        },
        _getProgress: function () {
            this.progress = Math.floor((this._loadedNum / this._urlList.length) * 100 + this._testPro * 100) / 100;
            return this.progress;
        }
    });

    //-----------------------------
    //  browser
    //-----------------------------
    gb.browser.getUserAgent = function () {
        var u = navigator.userAgent, app = navigator.appVersion;
        return {
            trident: u.indexOf('Trident') > -1, //IE内核
            presto: u.indexOf('Presto') > -1, //opera内核
            webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
            gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
            mobile: !(!u.match(/AppleWebKit.*Mobile.*/) || !!u.match(/AppleWebKit/)), //是否为移动终端    ??
            ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
            android: u.indexOf('Android') > -1, //android终端或者uc浏览器
            iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器
            iPod: u.indexOf('iPod') > -1, //是否为iPod或者QQHD浏览器
            iPad: u.indexOf('iPad') > -1, //是否iPad
            webApp: u.indexOf('Safari') == -1, //是否web应该程序，没有头部与底部
            isMac: u.indexOf('Mac') > -1,	//是否是mac终端
            isLinux: u.indexOf('Linux') > -1,//是否是linux系统
            isWeiXin: navigator.userAgent.indexOf('MicroMessenger') > -1//判断是不是微信浏览器
        };
    };
    gb.browser.isPc = function () {
        return ( !(gb.browser.getUserAgent().ios || gb.browser.getUserAgent().android) );
    };
    gb.browser.language = (navigator.browserLanguage || navigator.language).toLowerCase();
    //-----------------------------
    //  $ins.window
    //-----------------------------
    gb.window.getWidth = function () {
        return document.documentElement.clientWidth;
    };
    gb.window.getHeight = function () {
        return document.documentElement.clientHeight;
    };
    gb.window.sgResize = new gb.classes.Signal;
    gb.window.doResize = function () {
        this.sgResize.dispatch(this.getWidth(), this.getHeight());
    };
    gb.window.doResize();
    window.onresize = function () {
        gb.window.doResize();
    };
    if (!Array.prototype.indexOf) {
        Array.prototype.indexOf = function (elt, from) {
            var len = this.length >>> 0;
            var from = Number(arguments[1]) || 0;
            from = (from < 0) ? Math.ceil(from) : Math.floor(from);
            if (from < 0) from += len;
            for (; from < len; from++) {
                if (from in this && this[from] === elt) return from;
            }
            return -1;
        };
    }
    //-----------------------------
    //  $ins.form
    //-----------------------------
    gb.form.checkIsInput = function (value) {
        var require = new RegExp(/.+/);
        return require.test(value);
    };
    gb.form.checkEmail = function (value) {
        var email = new RegExp(/[_a-zA-Z\d\-\.]+@[_a-zA-Z\d\-]+(\.[_a-zA-Z\d\-]+)+$/);
        return email.test(value);
    };
    gb.form.checkUrl = function (value) {
        var url = new RegExp(/^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/);
        return url.test(value);
    };
    gb.form.checkNumber = function (value) {
        var number = new RegExp(/^\d+$/);
        return number.test(value);
    };
    gb.form.checkInteger = function (value) {
        var integer = new RegExp(/^[-\+]?\d+$/);
        return integer.test(value);
    };
    gb.form.checkFloat = function (value) {
        var float = new RegExp(/^[-\+]?\d+(\.\d+)?$/);
        return float.test(value);
    };
    gb.form.checkEnglish = function (value) {
        var english = new RegExp(/^[A-Za-z]+$/);
        return english.test(value);
    };
    gb.form.checkID15 = function (value) {
        //15位
        var id = new RegExp(/^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$/);
        return id.test(value);
    };
    gb.form.checkID18 = function (value) {
        //18位
        var id = new RegExp(/^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{4}$/);
        return id.test(value);
    };
    gb.form.checkMobile = function (value) {
        var re;
        var ss = value;
//		re = /^(13[0-9]{9})| (18[0-9]{9}) |(15[89][0-9]{8})$/
        re = /1[3-8]+\d{9}/;
        return re.test(ss);
    };
    gb.form.checkChina = function (value) {
        var china = new RegExp(/[^\u4E00-\u9FA5]/);
        return china.test(value);
    };
    gb.form.checkLength = function (value0, value1) {
        var _length;
        w
        if (value0.length >= value1) {
            _length = true;
        }
        else {
            _length = false;
        }
        return _length;
    }
})();

